//
//  UserDB.m
//  DialectShare
//
//  Created by timmy zhong on 3/30/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "UserDB.h"
#import "Const.h"
#import "FMDatabase.h"
#import "PathHelper.h"
#import "User.h"

@implementation UserDB
- (id)init
{
    self = [super init];
    if (self) {
        FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
        if ([db open]) {
            NSString* createTableStatement = [NSString stringWithFormat:
                                              @"""CREATE TABLE IF NOT EXISTS %@"""
                                              """(%@ INTEGER PRIMARY KEY, %@ TEXT, %@ TEXT, %@ TEXT,"""
                                              """%@ TEXT, %@ TEXT, %@ INTEGER, %@ INTEGER, %@ INTEGER, %@ INTEGER, %@ INTEGER, %@ INTEGER)""", 
                                              UserTableName, UserUid, UserAccount, UserPassword, UserName,
                                              UserAvatar, UserAuth, UserDialectCount, UserFollowCount, 
                                              UserFanCount, UserCommentCount, UserMoto, UserIsFollow];
            BOOL su = [db executeUpdate:createTableStatement]; 
            if (!su) {
                NSLog(@"fail to create table  %@  error  %@", UserTableName, [db lastErrorMessage]);
            }
            [db close];
        }
    }
    
    return self;
}

- (void)addUsers:(NSArray *)users
{
    FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
    if (![db open]) {
        NSLog(@"addUsers: fail to open DB error  %@", [db lastErrorMessage]);
        return;
    }
    
    [db beginTransaction];
    for (User *user in users) {
        
        NSString *sql = [NSString stringWithFormat:@"INSERT OR REPLACE INTO %@ (%@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", UserTableName , UserUid, UserAccount, UserPassword, UserName, UserAvatar, UserAuth, UserDialectCount, UserFollowCount, UserFanCount, UserCommentCount, UserMoto, UserIsFollow];
        [db executeUpdate:sql,
         [NSNumber numberWithInt:user.uid],
         user.account, 
         user.password,
         user.name,
         user.avatar,
         user.auth,
         [NSNumber numberWithInt:user.dialectCount],
         [NSNumber numberWithInt:user.followCount],
         [NSNumber numberWithInt:user.fanCount],
         [NSNumber numberWithInt:user.commentCount],
         user.moto,
         [NSNumber numberWithInt:user.isFollow]];
    }
    
    BOOL su = [db commit];
    if (!su) {
        NSLog(@"fail to add user error %@", [db lastErrorMessage]);
    }
    [db close];
    
}

- (NSArray *)condition:(NSString *)condition start:(NSInteger)start count:(NSInteger)count
{
    FMDatabase *db = [FMDatabase databaseWithPath:[PathHelper dbPath]];
    if (![db open]) {
        NSLog(@"getYuXis: fail to open DB error  %@", [db lastErrorMessage]);
        return nil;
    }
    
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ limit %d, %d", UserTableName, condition, start, count];
    FMResultSet *rs = [db executeQuery:sql];
    NSMutableArray *users = [[NSMutableArray alloc] initWithCapacity:20];
    while ([rs next]) {
        User *user = [[User alloc] init];
        user.uid = [rs intForColumn:UserUid];
        user.account = [rs stringForColumn:UserAccount];
        user.name = [rs stringForColumn:UserName];
        user.password = [rs stringForColumn:UserPassword];
        user.avatar = [rs stringForColumn:UserAvatar];
        user.auth = [rs stringForColumn:UserAuth];
        user.dialectCount = [rs intForColumn:UserDialectCount];
        user.followCount = [rs intForColumn:UserFollowCount];
        user.fanCount = [rs intForColumn:UserFanCount];
        user.commentCount = [rs intForColumn:UserCommentCount];
        user.moto = [rs stringForColumn:UserMoto];
        user.isFollow = [rs boolForColumn:UserIsFollow];
        [users addObject:user];
    }
    [db close];
    return [users autorelease];

}

- (User *)userOfID:(NSInteger)uid
{
    NSString *condition = [NSString stringWithFormat:@"%@=%d", UserUid, uid];
    NSArray *users = [self condition:condition start:0 count:2];
    if ([users count] > 0) {
        return [users objectAtIndex:0];
    }
    return nil;
}








@end








